import { Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    CreateOrUpdateRoleInput,
    RoleEditDto,
    RoleServiceProxy,
    PiciDto,
    PiciServiceProxy
} from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createOrEditPiciModal',
    templateUrl: './create-or-edit-pici.modal.component.html'
})
export class CreateOrEditPiciModalComponent extends AppComponentBase {
    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    pici = new PiciDto();
    constructor(injector: Injector, private _piciService: PiciServiceProxy) {
        super(injector);
    }

    show(piciId?: number): void {
        const self = this;
        self.active = true;

        if (!piciId) {
            self.pici = new PiciDto();
            self.modal.show();
            return;
        }

        self._piciService.get(piciId).subscribe(result => {
            self.pici = result;
            self.modal.show();
        });
    }

    onShown(): void {
        document.getElementById('PiciNameInput').focus();
    }

    save(): void {
        const self = this;

        this.saving = true;

        if (self.pici.id) {
            this._piciService
                .update(self.pici)
                .pipe(finalize(() => (this.saving = false)))
                .subscribe(() => {
                    self.saveAfter();
                });
        } else {
            this._piciService
                .create(self.pici)
                .pipe(finalize(() => (this.saving = false)))
                .subscribe(() => {
                    self.saveAfter();
                });
        }
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }

    private saveAfter() {
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(null);
    }
}
